package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.query.SalesChartQueryObject;
import cn.wolfcode.crm.service.ISalesChartService;
import cn.wolfcode.crm.util.MyJsonMapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("salesChart")
public class SalesChartController {
    @Autowired
    private ISalesChartService salesChartService;


    @RequestMapping("")
    public String view() {
        return "salesChart/list";
    }

    @RequestMapping("query")
    @ResponseBody
    public List query(@ModelAttribute("qo") SalesChartQueryObject qo, Map map){
        map.put( "groupType", SalesChartQueryObject.groupType );
        return salesChartService.SalesChart( qo );
    }

    @RequestMapping("saleByBar")
    public String saleByBar(@ModelAttribute("qo") SalesChartQueryObject qo, Model model) {

        List<Object> x = new ArrayList<>();
        List<Object> y = new ArrayList<>();
        List<Map<String, Object>> maps = salesChartService.SalesChart( qo );
        System.out.println( maps );
        for (Map<String, Object> map : maps) {
            System.out.println( map );
            x.add( map.get( "groupBy" ) );
            y.add( map.get( "amount" ) );
        }
        model.addAttribute( "groupBy", SalesChartQueryObject.groupType.get( qo.getGroupBy() ) );
        model.addAttribute( "x", MyJsonMapUtil.toJsonString( x ) );
        model.addAttribute( "y", MyJsonMapUtil.toJsonString( y ) );
        return "salesChart/saleByBar";
    }


    @RequestMapping("saleByPic")
    public String saleByPic(@ModelAttribute("qo") SalesChartQueryObject qo, Model model) {

        List<Object> x = new ArrayList<>();
        List<Object> datas = new ArrayList<>();
        List<Map<String, Object>> maps = salesChartService.SalesChart( qo );
        System.out.println( maps );
        for (Map<String, Object> map : maps) {
            System.out.println( map );
            Map<String, Object> obj = new HashMap<>();
            x.add( map.get( "groupBy" ) );
            obj.put( "name", map.get( "groupBy" ) );
            obj.put( "value", map.get( "amount" ) );
            datas.add( obj );
        }
        model.addAttribute( "groupBy", SalesChartQueryObject.groupType.get( qo.getGroupBy() ) );
        model.addAttribute( "x", MyJsonMapUtil.toJsonString( x ) );
        model.addAttribute( "datas", MyJsonMapUtil.toJsonString( datas ) );
        return "salesChart/saleByPic";
    }

}
